package org.sharkness.web.authority;

import java.util.List;

import org.sharkness.business.entity.User;
import org.sharkness.business.factory.PropertiesFactory;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.security.authentication.event.AbstractAuthenticationEvent;
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;

@SuppressWarnings({ "unchecked", "rawtypes" })
public class IncorrectPasswordEventListener  extends HibernateDaoSupport implements ApplicationListener {

	@Override
	public void onApplicationEvent(ApplicationEvent event) {
		
		String hql = PropertiesFactory.getSharknessProperties().getProperty("sharkness.database.username.hql");

		if (event instanceof AbstractAuthenticationEvent) {
			
			List<User> results = getHibernateTemplate().find(
				hql, new Object[] {
					((AbstractAuthenticationEvent)event).getAuthentication().getName()
				}
			);
				
			User user = results.get(0);
				
			if (event instanceof AuthenticationFailureBadCredentialsEvent) {
				
				user.setTries(user.getTries() + 1);
				
			} else if (event instanceof AuthenticationSuccessEvent) {
				
				user.setTries(0);
				
			}
			
			getHibernateTemplate().update(user);
			
		}
		
	}

}